package C034;

/**
 * ClassName: C02
 * Package: C034
 * Description:
 *
 * @Author BCXJ
 * @Create 2025/1/4 16:11
 * @Version 1.0
 * @Since 1.0
 */
public class Code02_ReverseNodesInkGroup {

    // 不要提交这个类
    public static class ListNode {
        public int val;
        public ListNode next;

        public ListNode(int x) {
            this.val = x;
        }
    }


    public static void main(String[] args) {
        ListNode node1 = new ListNode(1);
        ListNode node2 = new ListNode(2);
        ListNode node3 = new ListNode(3);
        ListNode node4 = new ListNode(4);
        ListNode node5 = new ListNode(5);
        node1.next = node2;
        node2.next = node3;
        node3.next = node4;
        node4.next = node5;
        ListNode node = reverseKGroup(node1, 2);

        while (node != null) {
            System.out.println(node.val);
            node = node.next;
        }
    }

    // 反转链表
    public static ListNode reverseKGroup(ListNode head, int k) {
        // 判断链表是否够长度
        ListNode end = teamEnd(head, k);
        if (null == end) {
            return head;
        }

        ListNode start = head;
        // 反转第一个链表快
        reverse(start, end);
        head = end;
        ListNode s2 = start.next;
        while ((end = teamEnd(s2, k)) != null) {
            reverse(s2, end);
            start.next = end;
            start = s2;
            s2 = start.next;
        }
        return head;
    }

    // 反转链表
    // start -> m1 -> m2 -> end
    // end -> m2 -> m1 -> start
    private static void reverse(ListNode start, ListNode end) {
        ListNode pre = null, cur = start, next = null;
        end = end.next;
        while (cur != end) {
            next = cur.next;
            cur.next = pre;
            pre = cur;
            cur = next;
        }
        start.next = end;
    }

    // 找出最后一个节点
    private static ListNode teamEnd(ListNode head, int k) {
        while (head != null && --k > 0) {
            head = head.next;
        }
        return head;
    }
}
